'use strict';

const moment = require('moment/moment');
const personnel = require('../model/personnel');

const Controller = require('egg').Controller;

const personnelAttributes = ['userName', 'branchPersonnel', 'department', 'birthDate', 'phone']

class QualificationController extends Controller {

  async createQualification() {
    const ctx = this.ctx;
    const params = ctx.request.body;
    const data = await ctx.model.Qualification.create(params);
    ctx.body = {
      code: 0,
      data,
      message: '创建成功',
    };
  }

  async queryQualification() {
    const ctx = this.ctx;
    const params = ctx.request.body;
    const {
      userName,
      pid,
      structure,
      qualification,
      registNum,
      age, //
      isLeader: leadType,
      suspension,
      pageSize = 10,
      current = 1,
    } = params
    const limit = Number(pageSize);
    const offset = limit * ((current || 1) - 1);
    const innerQuery = {};
    const query = {};
    if (userName) { innerQuery.where = { ...innerQuery.where, userName }; };
    // if (jobType) { innerQuery.where = { ...innerQuery.jobType, jobType }; };
    if (pid || pid === 0) { query.where = { ...query.where, pid }; };
    if (structure || structure == 0) { query.where = { ...query.where, structure } };
    if (qualification || qualification == 0) { query.where = { ...query.where, qualification } };
    if (registNum || registNum == 0) { query.where = { ...query.where, registNum } };
    if (leadType || leadType == 0) { query.where = { ...query.where, leadType } };
    if (suspension || suspension == 0) { query.where = { ...query.where, suspension } };
    const queryParams = {
      include: [
        {
          model: ctx.model.Personnel,
          attributes: personnelAttributes,
          ...innerQuery
        }
      ],
      ...query
    };
    let data = await ctx.model.Qualification.findAll({
      limit,
      offset,
      ...queryParams

    })

    const totalData = await ctx.model.Qualification.findAndCountAll(
      {
        ...queryParams
      }
    );
    ctx.body = {
      code: 0,
      data,
      pageInfo: {
        total: totalData.count,
        current,
        pageSize: Number(pageSize),
      },
      message: '查询成功',
    };
  }


  async getQualificationByPid() {
    const ctx = this.ctx;
    const { pid } = ctx.query
    const data = await ctx.model.Qualification.findAll({
      where: {
        pid: pid
      }
    })
    ctx.body = {
      code: 0,
      data,
      message: '查询成功',
    };
  }

}


module.exports = QualificationController;